// composables/useFetchApi.js
import {
	useToken
} from './useToken';

export const baseURL = 'https://api.flirtyzsex.com';
//export const baseURL = 'http://127.0.0.1:8000';

export function useFetchApi() {
	const {
		getToken,
		clearToken
	} = useToken();

	const fetchApi = async (url, method, data = {}, isFileUpload = false) => {
		const token = getToken();
		const headers = new Headers();

		if (!isFileUpload) {
			headers.append('Content-Type', 'application/json');
		}
		if (token) {
			headers.append('Authorization', `Bearer ${token}`);
		}

		let fullUrl = `${baseURL}${url}`;
		const fetchOptions = {
			method: method,
			headers: headers,
		};

		// 文件上传
		if (isFileUpload) {
			const formData = new FormData();
			const file = data.file;
			formData.append('file', file, file.name || 'default_filename.txt');
			fetchOptions.body = formData;
		}
		// GET 请求处理参数
		else if (method === 'GET') {
			const params = new URLSearchParams(data).toString();
			if (params) {
				fullUrl += `?${params}`;
			}
		}
		// POST/PUT/DELETE 请求处理 JSON 数据
		else {
			fetchOptions.body = JSON.stringify(data);
		}

		try {
			const response = await fetch(fullUrl, fetchOptions);
			const responseData = await response.json();

			if (!response.ok) {
				// 处理 token 过期或未授权情况
				if (response.status === 401) {
					console.error('Token expired or invalid');
					clearToken(); // 使用封装的清除函数
					return;
				}
				throw responseData;
			}
			return responseData;
		} catch (error) {
			console.error('Fetch API error:', error);
			throw error;
		}
	};

	// 封装的请求方法
	return {
		get: (url, params = {}) => fetchApi(url, 'GET', params),
		post: (url, data) => fetchApi(url, 'POST', data),
		put: (url, data) => fetchApi(url, 'PUT', data),
		patch: (url, data) => fetchApi(url, 'PATCH', data),
		remove: (url, data) => fetchApi(url, 'DELETE', data),
		upload: (url, file) => fetchApi(url, 'POST', {
			file
		}, true),
	};
}